package cn.harry.cabinet.view.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.DialogFragment
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.Card
import java.util.Date

/**
 * 卡片表单对话框
 * 用于添加和编辑卡片
 */
class CardFormDialogFragment(
    private val card: Card? = null,
    private val onCardSaved: (Card) -> Unit
) : DialogFragment() {

    private lateinit var etCardNumber: EditText
    private lateinit var etName: EditText
    private lateinit var etType: EditText
    private lateinit var etRemark: EditText
    private lateinit var spinnerStatus: Spinner
    private lateinit var btnSave: Button
    private lateinit var btnCancel: Button

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_card_form, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化视图
        etCardNumber = view.findViewById(R.id.etCardNumber)
        etName = view.findViewById(R.id.etName)
        etType = view.findViewById(R.id.etType)
        etRemark = view.findViewById(R.id.etRemark)
        spinnerStatus = view.findViewById(R.id.spinnerStatus)
        btnSave = view.findViewById(R.id.btnSave)
        btnCancel = view.findViewById(R.id.btnCancel)

        // 设置标题
        val title = view.findViewById<TextView>(R.id.dialogTitle)
        title.text = if (card == null) "添加卡片" else "编辑卡片"

        // 设置状态下拉框
        setupStatusSpinner()

        // 如果是编辑模式，填充现有数据
        card?.let { fillCardData(it) }

        // 设置按钮点击事件
        btnSave.setOnClickListener { saveCard() }
        btnCancel.setOnClickListener { dismiss() }
    }

    override fun onStart() {
        super.onStart()
        // 设置对话框大小
        dialog?.window?.setLayout(
            (resources.displayMetrics.widthPixels * 0.9).toInt(),
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
    }

    private fun setupStatusSpinner() {
        val statuses = arrayOf("启用", "禁用")
        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, statuses)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerStatus.adapter = adapter
    }

    private fun fillCardData(card: Card) {
        etCardNumber.setText(card.cardNumber)
        etName.setText(card.name)
        etType.setText(card.type)
        etRemark.setText(card.remark)

        // 设置状态
        val statusIndex = when (card.status) {
            Card.STATUS_ENABLED -> 0
            Card.STATUS_DISABLED -> 1
            else -> 0
        }
        spinnerStatus.setSelection(statusIndex)
    }

    private fun saveCard() {
        // 验证输入
        val cardNumber = etCardNumber.text.toString().trim()
        if (cardNumber.isEmpty()) {
            Toast.makeText(context, "请输入卡号", Toast.LENGTH_SHORT).show()
            return
        }

        val name = etName.text.toString().trim()
        if (name.isEmpty()) {
            Toast.makeText(context, "请输入名称", Toast.LENGTH_SHORT).show()
            return
        }

        val type = etType.text.toString().trim()
        if (type.isEmpty()) {
            Toast.makeText(context, "请输入类型", Toast.LENGTH_SHORT).show()
            return
        }

        val remark = etRemark.text.toString().trim()
        val status = when (spinnerStatus.selectedItemPosition) {
            0 -> Card.STATUS_ENABLED
            1 -> Card.STATUS_DISABLED
            else -> Card.STATUS_ENABLED
        }

        // 创建或更新卡片对象
        val newCard = if (card == null) {
            // 添加模式
            Card(
                cardNumber = cardNumber,
                name = name,
                type = type,
                remark = remark,
                status = status,
                createTime = Date(),
                updateTime = Date()
            )
        } else {
            // 编辑模式
            card.copy(
                cardNumber = cardNumber,
                name = name,
                type = type,
                remark = remark,
                status = status,
                updateTime = Date()
            )
        }

        // 回调保存
        onCardSaved(newCard)
        dismiss()
    }
}
